import * as vscode from "vscode";

import ts from "typescript";
import * as path from "path";
import * as fs from "fs";
import { $context } from "@ap/extension";
import { getESCCfg } from "./componentPresets";

/**
 * 组件使用统计相关接口定义
 */

/**
 * 组件引用基础信息
 */
interface ComponentReference {
  filePath: string; // 引用文件路径
  position: vscode.Position; // 引用位置
  lineText: string; // 引用行文本
}

/**
 * 属性引用信息
 */
interface PropertyReference extends ComponentReference {
  propertyName: string; // 属性名称
}

/**
 * 属性使用统计
 */
interface PropertyUsage {
  propertyName: string; // 属性名称
  count: number; // 引用次数
  filePath: string; // 定义文件路径
  position: vscode.Position; // 定义位置
  references: PropertyReference[]; // 引用列表
}

/**
 * 方法引用信息
 */
interface MethodReference extends ComponentReference {
  methodName: string; // 方法名称
}

/**
 * 方法使用统计
 */
interface MethodUsage {
  methodName: string; // 方法名称
  count: number; // 引用次数
  filePath: string; // 定义文件路径
  position: vscode.Position; // 定义位置
  references: MethodReference[]; // 引用列表
}

/**
 * 组件使用统计
 */
interface ComponentUsage {
  className: string; // 组件类名
  count: number; // 使用次数
  filePath: string; // 定义文件路径
  position: vscode.Position; // 定义位置
  references: ComponentReference[]; // 引用列表
  methods: Map<string, MethodUsage>; // 方法使用统计
  properties: Map<string, PropertyUsage>; // 属性使用统计
  isNodeSystem?: boolean; // 是否为NodeSystem类
}

// 存储组件使用情况
const componentUsages: Map<string, ComponentUsage> = new Map();

// 缓存已分析过的文件及其最后修改时间
const analyzedFiles: Map<string, number> = new Map();

// CodeLens提供器
export class ComponentUsageCodeLensProvider implements vscode.CodeLensProvider {
  private _onDidChangeCodeLenses: vscode.EventEmitter<void> =
    new vscode.EventEmitter<void>();
  public readonly onDidChangeCodeLenses: vscode.Event<void> =
    this._onDidChangeCodeLenses.event;

  constructor() {
    // 监听文件变化
    vscode.workspace.onDidSaveTextDocument((document) => {
      // 在重新分析前，记录当前文件中的组件
      const oldComponents = new Set<string>();
      for (const [className, usage] of componentUsages.entries()) {
        if (usage.filePath === document.uri.fsPath) {
          oldComponents.add(className);
        }
      }

      analyzeComponentUsage(document).then(() => {
        // 检查并删除已不存在的组件
        for (const className of oldComponents) {
          const usage = componentUsages.get(className);
          if (usage && usage.filePath === document.uri.fsPath) {
            // 检查文件内容是否还包含该类的定义
            const content = document.getText();
            const classPattern = new RegExp(`class\\s+${className}\\s+`);
            if (!classPattern.test(content)) {
              componentUsages.delete(className);
            }
          }
        }
        this._onDidChangeCodeLenses.fire();
      });
    });

    // 监听文件删除
    vscode.workspace.onDidDeleteFiles(async (e) => {
      for (const file of e.files) {
        // 清理已分析文件记录
        analyzedFiles.delete(file.fsPath);

        // 清理被删除文件中的组件引用
        for (const [className, usage] of componentUsages.entries()) {
          usage.references = usage.references.filter(
            (ref) => ref.filePath !== file.fsPath,
          );
          usage.count = usage.references.length;

          // 如果组件定义文件被删除，移除该组件
          if (usage.filePath === file.fsPath) {
            componentUsages.delete(className);
          }
        }

        this._onDidChangeCodeLenses.fire();
      }
    });

    // 监听文件重命名
    vscode.workspace.onDidRenameFiles(async (e) => {
      for (const file of e.files) {
        // 更新已分析文件记录
        const lastAnalyzed = analyzedFiles.get(file.oldUri.fsPath);
        if (lastAnalyzed) {
          analyzedFiles.delete(file.oldUri.fsPath);
          analyzedFiles.set(file.newUri.fsPath, lastAnalyzed);
        }

        // 更新组件引用中的文件路径
        for (const usage of componentUsages.values()) {
          // 更新组件定义文件路径
          if (usage.filePath === file.oldUri.fsPath) {
            usage.filePath = file.newUri.fsPath;
          }

          // 更新引用路径
          usage.references.forEach((ref) => {
            if (ref.filePath === file.oldUri.fsPath) {
              ref.filePath = file.newUri.fsPath;
            }
          });
        }

        this._onDidChangeCodeLenses.fire();
      }
    });
  }

  public provideCodeLenses(
    document: vscode.TextDocument,
    token: vscode.CancellationToken,
  ): vscode.CodeLens[] | Thenable<vscode.CodeLens[]> {
    const codeLenses: vscode.CodeLens[] = [];

    // 查找当前文件中定义的组件类
    for (const [className, usage] of componentUsages.entries()) {
      if (usage.filePath === document.uri.fsPath) {
        const range = new vscode.Range(
          usage.position,
          new vscode.Position(
            usage.position.line,
            usage.position.character + className.length,
          ),
        );

        const componentCodeLens = new vscode.CodeLens(range, {
          title: `${usage.isNodeSystem ? "神岛节点系统" : "神岛节点组件"} | ${usage.count} 个引用`,
          command: "ap.codelens.showComponentReferences",
          arguments: [usage],
          tooltip: "点击查看该组件引用情况",
        });
        codeLenses.push(componentCodeLens);

        // 为每个方法添加CodeLens
        for (const methodUsage of usage.methods.values()) {
          const methodRange = new vscode.Range(
            methodUsage.position,
            new vscode.Position(
              methodUsage.position.line,
              methodUsage.position.character + methodUsage.methodName.length,
            ),
          );

          const methodCodeLens = new vscode.CodeLens(methodRange, {
            title: `${methodUsage.count} 个引用`,
            command: "ap.codelens.showMethodReferences",
            arguments: [methodUsage],
            tooltip: "点击查看该方法引用情况",
          });
          codeLenses.push(methodCodeLens);
        }

        // 为每个属性添加CodeLens
        for (const propertyUsage of usage.properties.values()) {
          const propertyRange = new vscode.Range(
            propertyUsage.position,
            new vscode.Position(
              propertyUsage.position.line,
              propertyUsage.position.character +
                propertyUsage.propertyName.length,
            ),
          );

          const propertyCodeLens = new vscode.CodeLens(propertyRange, {
            title: `${propertyUsage.count} 个引用`,
            command: "ap.codelens.showPropertyReferences",
            arguments: [propertyUsage],
            tooltip: "点击查看该属性引用情况",
          });
          codeLenses.push(propertyCodeLens);
        }
      }
    }

    return codeLenses;
  }
}

// 分析项目中的组件使用情况
async function analyzeComponentUsage(document?: vscode.TextDocument) {
  // 获取ECS配置
  const ecsCfg = await getESCCfg();
  if (!ecsCfg.server && !ecsCfg.client) {
    return false;
  }

  // 根据当前文件路径和ECS配置确定搜索范围
  let searchPatterns: string[] = [];
  if (document) {
    const filePath = document.uri.fsPath;
    if (filePath.includes("/server/") || filePath.includes("\\server\\")) {
      if (ecsCfg.server) {
        searchPatterns.push("**/server/**/*.{ts,tsx}");
      }
    } else if (
      filePath.includes("/client/") ||
      filePath.includes("\\client\\")
    ) {
      if (ecsCfg.client) {
        searchPatterns.push("**/client/**/*.{ts,tsx}");
      }
    } else if (
      filePath.includes("/shares/") ||
      filePath.includes("\\shares\\")
    ) {
      searchPatterns.push("**/shares/**/*.{ts,tsx}");
    }
  } else {
    if (ecsCfg.server) {
      searchPatterns.push("**/server/**/*.{ts,tsx}");
    }
    if (ecsCfg.client) {
      searchPatterns.push("**/client/**/*.{ts,tsx}");
    }
    searchPatterns.push("**/shares/**/*.{ts,tsx}");
  }

  if (searchPatterns.length === 0) {
    return;
  }

  // 获取指定范围内的TypeScript文件
  let tsFiles: vscode.Uri[] = [];
  for (const pattern of searchPatterns) {
    const files = await vscode.workspace.findFiles(
      pattern,
      "**/node_modules/**",
    );
    tsFiles = tsFiles.concat(files);
  }

  if (tsFiles.length === 0) {
    return;
  }

  // 首先识别所有继承自Component的类
  const componentClasses: string[] = [];

  for (const file of tsFiles) {
    try {
      const content = fs.readFileSync(file.fsPath, "utf8");
      const sourceFile = ts.createSourceFile(
        file.fsPath,
        content,
        ts.ScriptTarget.Latest,
        true,
      );

      // 遍历AST查找继承自Component的类
      ts.forEachChild(sourceFile, (node) => {
        if (ts.isClassDeclaration(node) && node.heritageClauses) {
          classFor: for (const clause of node.heritageClauses) {
            let isApclass = false;
            for (const type of clause.types) {
              const baseTypeName = type.expression.getText();
              if (
                (baseTypeName.includes("Component") ||
                  baseTypeName.includes("NodeSystem")) &&
                node.name
              ) {
                if (baseTypeName.includes("Component")) {
                  const decorators = ts.getDecorators(node);
                  if (decorators) {
                    for (const decorator of decorators) {
                      const decoratorText = decorator.expression.getText();
                      if (decoratorText.includes("apclass")) {
                        isApclass = true;
                        break;
                      }
                    }
                  }
                  if (!isApclass) {
                    continue classFor;
                  }
                }
                const className = node.name.text;
                componentClasses.push(className);

                // 记录类定义位置
                const start = node.name.getStart(sourceFile);
                const position =
                  sourceFile.getLineAndCharacterOfPosition(start);

                // 收集组件类中的方法和属性信息
                const methods = new Map<string, MethodUsage>();
                const properties = new Map<string, PropertyUsage>();
                if (node.members) {
                  for (const member of node.members) {
                    if (ts.isMethodDeclaration(member) && member.name) {
                      const methodName = member.name.getText();
                      if (
                        methodName === "start" ||
                        methodName === "update" ||
                        methodName === "onDestroy" ||
                        methodName === "onEnable" ||
                        methodName === "onDisable" ||
                        methodName === "onLoad" ||
                        methodName === "lateUpdate" ||
                        methodName === "postUpdate" ||
                        methodName === "onEntityNodeAdded" ||
                        methodName === "onEntityNodeRemoved"
                      ) {
                        continue;
                      }
                      const methodStart = member.name.getStart(sourceFile);
                      const methodPosition =
                        sourceFile.getLineAndCharacterOfPosition(methodStart);

                      methods.set(methodName, {
                        methodName,
                        count: 0,
                        filePath: file.fsPath,
                        position: new vscode.Position(
                          methodPosition.line,
                          methodPosition.character,
                        ),
                        references: [],
                      });
                    } else if (
                      ts.isPropertyDeclaration(member) &&
                      member.name
                    ) {
                      const propertyName = member.name.getText();
                      const propertyStart = member.name.getStart(sourceFile);
                      const propertyPosition =
                        sourceFile.getLineAndCharacterOfPosition(propertyStart);

                      properties.set(propertyName, {
                        propertyName,
                        count: 0,
                        filePath: file.fsPath,
                        position: new vscode.Position(
                          propertyPosition.line,
                          propertyPosition.character,
                        ),
                        references: [],
                      });
                    }
                  }
                }

                componentUsages.set(className, {
                  className,
                  count: 0,
                  filePath: file.fsPath,
                  position: new vscode.Position(
                    position.line,
                    position.character,
                  ),
                  references: [],
                  methods,
                  properties,
                  isNodeSystem: baseTypeName.includes("NodeSystem"),
                });
              }
            }
          }
        }
      });
    } catch (error) {
      console.error(`Error analyzing file: ${file.fsPath}`, error);
      continue;
    }
  }

  // 然后统计每个组件类被实例化的次数
  for (const file of tsFiles) {
    try {
      const content = fs.readFileSync(file.fsPath, "utf8");
      const sourceFile = ts.createSourceFile(
        file.fsPath,
        content,
        ts.ScriptTarget.Latest,
        true,
      );

      // 用于追踪变量声明和引用的映射
      const variableComponentMap = new Map<string, string>();
      const variableTypeMap = new Map<string, string>();

      // 遍历AST查找组件实例化和方法引用
      ts.forEachChild(sourceFile, function visit(node) {
        // 检查NodeSystem实例化
        if (ts.isNewExpression(node) && ts.isIdentifier(node.expression)) {
          const className = node.expression.text;
          if (componentClasses.includes(className)) {
            const usage = componentUsages.get(className);
            if (usage && usage.isNodeSystem) {
              const start = node.getStart(sourceFile);
              const position = sourceFile.getLineAndCharacterOfPosition(start);
              const lineText = sourceFile.getFullText().split("\n")[
                position.line
              ];

              const existingRef = usage.references.find(
                (ref) =>
                  ref.filePath === file.fsPath &&
                  ref.position.line === position.line &&
                  ref.position.character === position.character,
              );

              if (!existingRef) {
                usage.references.push({
                  filePath: file.fsPath,
                  position: new vscode.Position(
                    position.line,
                    position.character,
                  ),
                  lineText: lineText.trim(),
                });
                usage.count = usage.references.length;
              }
            }
          }
        }

        // 处理变量声明
        if (ts.isVariableDeclaration(node) && node.initializer) {
          // 处理new表达式
          if (
            ts.isNewExpression(node.initializer) &&
            ts.isIdentifier(node.initializer.expression)
          ) {
            const className = node.initializer.expression.text;
            if (node.name && ts.isIdentifier(node.name)) {
              variableTypeMap.set(node.name.text, className);
            }
          }
          // 处理getComponent调用
          if (
            ts.isCallExpression(node.initializer) &&
            ts.isPropertyAccessExpression(node.initializer.expression)
          ) {
            if (node.initializer.arguments.length > 0) {
              const arg = node.initializer.arguments[0];
              let componentName = arg.getText();

              if (ts.isStringLiteral(arg)) {
                // 处理字符串类型参数
                componentName = arg.text;
                // 移除可能的引号
                componentName = componentName.replace(/["']/g, "");
              } else if (ts.isIdentifier(arg)) {
                componentName = arg.text;
              }

              if (node.name && ts.isIdentifier(node.name)) {
                variableComponentMap.set(node.name.text, componentName);
              }
            }
          }
        }

        // 处理方法调用和属性访问
        if (ts.isPropertyAccessExpression(node)) {
          const objectName = node.expression.getText();
          const memberName = node.name.text;
          const objectType = variableTypeMap.get(objectName);

          if (objectType && componentClasses.includes(objectType)) {
            const usage = componentUsages.get(objectType);
            if (usage) {
              // 处理方法调用
              if (ts.isCallExpression(node.parent)) {
                const methodUsage = usage.methods.get(memberName);
                if (methodUsage) {
                  const start = node.parent.getStart(sourceFile);
                  const position =
                    sourceFile.getLineAndCharacterOfPosition(start);
                  const lineText = sourceFile.getFullText().split("\n")[
                    position.line
                  ];

                  const existingRef = methodUsage.references.find(
                    (ref) =>
                      ref.filePath === file.fsPath &&
                      ref.position.line === position.line &&
                      ref.position.character === position.character,
                  );

                  if (!existingRef) {
                    methodUsage.references.push({
                      filePath: file.fsPath,
                      position: new vscode.Position(
                        position.line,
                        position.character,
                      ),
                      lineText: lineText.trim(),
                      methodName: memberName,
                    });
                    methodUsage.count = methodUsage.references.length;
                  }
                }
              }
              // 处理属性访问
              else {
                const propertyUsage = usage.properties.get(memberName);
                if (propertyUsage) {
                  const start = node.getStart(sourceFile);
                  const position =
                    sourceFile.getLineAndCharacterOfPosition(start);
                  const lineText = sourceFile.getFullText().split("\n")[
                    position.line
                  ];

                  const existingRef = propertyUsage.references.find(
                    (ref) =>
                      ref.filePath === file.fsPath &&
                      ref.position.line === position.line &&
                      ref.position.character === position.character,
                  );

                  if (!existingRef) {
                    propertyUsage.references.push({
                      filePath: file.fsPath,
                      position: new vscode.Position(
                        position.line,
                        position.character,
                      ),
                      lineText: lineText.trim(),
                      propertyName: memberName,
                    });
                    propertyUsage.count = propertyUsage.references.length;
                  }
                }
              }
            }
          }
        }

        // 处理组件实例化
        if (
          ts.isCallExpression(node) &&
          ts.isPropertyAccessExpression(node.expression)
        ) {
          if (node.arguments.length > 0) {
            const arg = node.arguments[0];
            let componentName = arg.getText();

            if (ts.isStringLiteral(arg)) {
              componentName = arg.text;
              // 移除可能的引号
              componentName = componentName.replace(/["']/g, "");
            } else if (ts.isIdentifier(arg)) {
              componentName = arg.text;
            }

            // 更新组件使用统计
            if (componentClasses.includes(componentName)) {
              const usage = componentUsages.get(componentName);
              if (usage) {
                // 检查是否已存在相同位置的引用
                const start = node.getStart(sourceFile);
                const position =
                  sourceFile.getLineAndCharacterOfPosition(start);
                const lineText = sourceFile.getFullText().split("\n")[
                  position.line
                ];

                const existingRef = usage.references.find(
                  (ref) =>
                    ref.filePath === file.fsPath &&
                    ref.position.line === position.line &&
                    ref.position.character === position.character,
                );

                if (!existingRef) {
                  usage.references.push({
                    filePath: file.fsPath,
                    position: new vscode.Position(
                      position.line,
                      position.character,
                    ),
                    lineText: lineText.trim(),
                  });
                  usage.count = usage.references.length;
                }
              }
            }
          }
        }

        // 检查方法引用和属性访问
        if (ts.isPropertyAccessExpression(node)) {
          let componentName = node.expression.getText();
          const memberName = node.name.text;

          // 处理变量引用
          if (ts.isIdentifier(node.expression)) {
            const mappedComponent = variableComponentMap.get(componentName);
            if (mappedComponent) {
              componentName = mappedComponent;
            }
          }

          // 处理this引用
          if (componentName === "this") {
            // 获取当前类名
            let currentClass: ts.Node | undefined = node;
            while (currentClass && !ts.isClassDeclaration(currentClass)) {
              currentClass = currentClass.parent;
            }
            if (currentClass && currentClass.name) {
              componentName = currentClass.name.text;
            }
          }

          // 查找对应的组件
          for (const [className, usage] of componentUsages.entries()) {
            if (componentName.includes(className)) {
              // 如果是方法引用
              if (ts.isCallExpression(node.parent)) {
                const methodUsage = usage.methods.get(memberName);
                if (methodUsage) {
                  const start = node.parent.getStart(sourceFile);
                  const position =
                    sourceFile.getLineAndCharacterOfPosition(start);
                  const lineText = sourceFile.getFullText().split("\n")[
                    position.line
                  ];

                  const existingRef = methodUsage.references.find(
                    (ref) =>
                      ref.filePath === file.fsPath &&
                      ref.position.line === position.line &&
                      ref.position.character === position.character,
                  );

                  if (!existingRef) {
                    methodUsage.references.push({
                      filePath: file.fsPath,
                      position: new vscode.Position(
                        position.line,
                        position.character,
                      ),
                      lineText: lineText.trim(),
                      methodName: memberName,
                    });
                    methodUsage.count = methodUsage.references.length;
                  }
                }
              }
              // 如果是属性访问
              else {
                let targetComponentName = componentName;

                // 处理变量引用的情况
                if (ts.isIdentifier(node.expression)) {
                  const mappedComponent =
                    variableComponentMap.get(componentName);
                  if (mappedComponent) {
                    targetComponentName = mappedComponent;
                  }
                }

                // 处理this引用的情况
                if (componentName === "this") {
                  let currentClass: ts.Node | undefined = node;
                  while (currentClass && !ts.isClassDeclaration(currentClass)) {
                    currentClass = currentClass.parent;
                  }
                  if (
                    currentClass &&
                    ts.isClassDeclaration(currentClass) &&
                    currentClass.name
                  ) {
                    targetComponentName = currentClass.name.text;
                  }
                }

                // 查找对应组件的属性
                for (const [className, usage] of componentUsages.entries()) {
                  if (targetComponentName.includes(className)) {
                    const propertyUsage = usage.properties.get(memberName);
                    if (propertyUsage) {
                      const start = node.getStart(sourceFile);
                      const position =
                        sourceFile.getLineAndCharacterOfPosition(start);
                      const lineText = sourceFile.getFullText().split("\n")[
                        position.line
                      ];

                      const existingRef = propertyUsage.references.find(
                        (ref) =>
                          ref.filePath === file.fsPath &&
                          ref.position.line === position.line &&
                          ref.position.character === position.character,
                      );

                      if (!existingRef) {
                        propertyUsage.references.push({
                          filePath: file.fsPath,
                          position: new vscode.Position(
                            position.line,
                            position.character,
                          ),
                          lineText: lineText.trim(),
                          propertyName: memberName,
                        });
                        propertyUsage.count = propertyUsage.references.length;
                      }
                    }
                  }
                }
              }
            }
          }
        }

        // 递归遍历子节点
        ts.forEachChild(node, visit);
      });

      // 更新文件分析时间戳
      analyzedFiles.set(file.fsPath, Date.now());
    } catch (error) {
      console.error(`Error analyzing file references: ${file.fsPath}`, error);
      continue;
    }
  }
}

export async function showPropertyReferences(usage: PropertyUsage) {
  if (!usage.references || usage.references.length === 0) {
    return;
  }

  const items = usage.references.map((ref) => ({
    label: path.basename(ref.filePath),
    description: ref.lineText.trim(),
    detail: ref.filePath,
    reference: ref,
  }));

  const selected = await vscode.window.showQuickPick(items, {
    placeHolder: `选择属性 ${usage.propertyName} 的引用位置`,
  });

  if (selected) {
    const document = await vscode.workspace.openTextDocument(
      selected.reference.filePath,
    );
    const editor = await vscode.window.showTextDocument(document);
    const position = selected.reference.position;

    editor.selection = new vscode.Selection(position, position);
    editor.revealRange(
      new vscode.Range(position, position),
      vscode.TextEditorRevealType.InCenter,
    );
  }
}

export async function showMethodReferences(usage: MethodUsage) {
  if (!usage.references || usage.references.length === 0) {
    return;
  }

  const items = usage.references.map((ref) => ({
    label: path.basename(ref.filePath),
    description: ref.lineText.trim(),
    detail: ref.filePath,
    reference: ref,
  }));

  const selected = await vscode.window.showQuickPick(items, {
    placeHolder: `选择方法 ${usage.methodName} 的引用位置`,
  });

  if (selected) {
    const document = await vscode.workspace.openTextDocument(
      selected.reference.filePath,
    );
    const editor = await vscode.window.showTextDocument(document);
    const position = selected.reference.position;

    editor.selection = new vscode.Selection(position, position);
    editor.revealRange(
      new vscode.Range(position, position),
      vscode.TextEditorRevealType.InCenter,
    );
  }
}

export async function showComponentReferences(usage: ComponentUsage) {
  if (!usage.references || usage.references.length === 0) {
    return;
  }

  const items = usage.references.map((ref) => ({
    label: path.basename(ref.filePath),
    description: ref.lineText.trim(),
    detail: ref.filePath,
    reference: ref,
  }));

  const selected = await vscode.window.showQuickPick(items, {
    placeHolder: `选择 ${usage.className} 的引用位置`,
  });

  if (selected) {
    const document = await vscode.workspace.openTextDocument(
      selected.reference.filePath,
    );
    const editor = await vscode.window.showTextDocument(document);
    const position = selected.reference.position;

    // 移动到引用位置并高亮显示
    editor.selection = new vscode.Selection(position, position);
    editor.revealRange(
      new vscode.Range(position, position),
      vscode.TextEditorRevealType.InCenter,
    );
  }
}
/**
 * 显示组件统计信息
 */
export async function showComponentStats() {
  // 获取所有组件使用情况
  const items = Array.from(componentUsages.values()).map((usage) => ({
    label: `${usage.className} (${usage.count} 个引用) ${usage.isNodeSystem ? "[NodeSystem]" : "[Component]"}`,
    description: path.basename(usage.filePath),
    detail: `定义于 ${usage.filePath}:${usage.position.line + 1}`,
    usage: usage,
  }));

  // 按使用次数降序排序
  items.sort((a, b) => b.usage.count - a.usage.count);

  const selected = await vscode.window.showQuickPick(items, {
    placeHolder: "选择组件查看详细信息",
  });

  if (selected) {
    const document = await vscode.workspace.openTextDocument(
      selected.usage.filePath,
    );
    const editor = await vscode.window.showTextDocument(document);
    const position = selected.usage.position;

    // 移动到组件定义位置并高亮显示
    editor.selection = new vscode.Selection(position, position);
    editor.revealRange(
      new vscode.Range(position, position),
      vscode.TextEditorRevealType.InCenter,
    );
  }
  return items;
}

export async function componentUsageProvider() {
  // 初始分析
  const activeEditor = vscode.window.activeTextEditor;

  analyzeComponentUsage(activeEditor?.document);

  // 监听文件变化
  // 清理超过1小时未使用的缓存
  setInterval(() => {
    const now = Date.now();
    for (const [filePath, timestamp] of analyzedFiles.entries()) {
      if (now - timestamp > 3600000) {
        // 1 hour
        analyzedFiles.delete(filePath);
      }
    }
  }, 3600000); // Check every hour

  const fileWatcher = vscode.workspace.createFileSystemWatcher("**/*.{ts}");
  fileWatcher.onDidChange((uri) => {
    const document = vscode.workspace.textDocuments.find(
      (doc) => doc.uri.fsPath === uri.fsPath,
    );
    analyzeComponentUsage(document);
  });
  fileWatcher.onDidCreate((uri) => {
    const document = vscode.workspace.textDocuments.find(
      (doc) => doc.uri.fsPath === uri.fsPath,
    );
    analyzeComponentUsage(document);
  });
  fileWatcher.onDidDelete((uri) => {
    const document = vscode.workspace.textDocuments.find(
      (doc) => doc.uri.fsPath === uri.fsPath,
    );
    analyzeComponentUsage(document);
  });

  $context.subscriptions.push(fileWatcher);
}
